package com.ptt.sqm.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ptt.sqm.component.ImageAdapter;
import com.ptt.sqm.component.SpinnerObject;
import com.ptt.sqm.model.AssessItemChoice5018;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.AssessSuggestion5034;
import com.ptt.sqm.model.AssessSuggestion5034List;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.ContactImage;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.MainSuggestion;
import com.ptt.sqm.model.MainSuggestionList;
import com.ptt.sqm.model.PriorSuggestion;
import com.ptt.sqm.model.PriorSuggestionList;
import com.ptt.sqm.model.SuggestionImage;
import com.ptt.sqm.model.SuggestionImageList;
import com.ptt.sqm.session.SavedAssessTran;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WebserviceUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.DownloadCall;
import com.ptt.sqm.ws.UploadCall;
import com.ptt.sqmonmobile.R;

/**
 * A simple {@link Fragment} subclass. Activities that contain this fragment
 * must implement the {@link CommentAssessAA.OnFragmentInteractionListener}
 * interface to handle interaction events. Use the
 * {@link CommentAssessAA#newInstance} factory method to create an instance of
 * this fragment.
 * 
 */
public class CommentAssessFragment extends DefaultFragment implements AsyncResponse, DecrementCallback {
	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";

	// Create Webservice class object
	private DefaultTask mTask = null;

	private DownloadCall downloadCall = null;

	// private UploadCall uploadCall = null;

	private static CommentAssessFragment fragment;

	private OnFragmentInteractionListener mListener;

	private View imageEntryView;

	private View inputEntryView;

	private List<AssessSuggestion5034> priorSuggestList = new LinkedList<AssessSuggestion5034>();

	private List<AssessSuggestion5034> currentSuggestList = new LinkedList<AssessSuggestion5034>();

	private MainSuggestionList mainSuggestionList;

	private List<String> deleteImageList = new ArrayList<String>();
	private List<String> tempImageList = new ArrayList<String>();

	private String cameraFileName;
	private String originalName;
	// Arguments
	private AssessItemList items;
	private AssessTran saveAssessTran;
	private String subjectId;
	private String itemId;

	private int currentIndex;
	private int priorIndex;
	private int curSubject;

	private String projCycleStationId;

	// Saved Assess Tran
	private SavedAssessTran savedTranPref;

	private boolean isSubmit;

	private Login login;

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment CommentAssess.
	 */
	// TODO: Rename and change types and number of parameters
	public static CommentAssessFragment newInstance(int sectionNumber, AssessItemList items, AssessTran saveAssessTran, String subjectId, String itemId, int curSubject) {
		fragment = new CommentAssessFragment(items, saveAssessTran, subjectId, itemId, curSubject);
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public CommentAssessFragment(AssessItemList items, AssessTran saveAssessTran, String subjectId, String itemId, int curSubject) {
		// Required empty public constructor
		this.items = items;
		this.saveAssessTran = saveAssessTran;
		this.subjectId = subjectId;
		this.itemId = itemId;
		this.curSubject = curSubject;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		login = session.getUserDetails();

		// Show Header
		final AssessItemChoice5018 AssessItemChoice5018 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId).Items.get(0).AssessItemChoiceMap.get(itemId);
		((TextView) view.findViewById(R.id.station)).setText(items.stationId + AppUtil.SPACE + items.stationName);
		((TextView) view.findViewById(R.id.project_assess)).setText(items.projectName);
		((TextView) view.findViewById(R.id.cycle_assess)).setText(items.cycle);
		((TextView) view.findViewById(R.id.assess_date)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.CreateDate));
		((TextView) view.findViewById(R.id.item_assess)).setText(AssessItemChoice5018.AssessSubjectName);
		((TextView) view.findViewById(R.id.choice_assess)).setText(AssessItemChoice5018.AssessItemName);
		((TextView) view.findViewById(R.id.point_assess)).setText(AssessItemChoice5018.AssessChoicePoint);
		((TextView) view.findViewById(R.id.pointdesc_assess)).setText(AssessItemChoice5018.AssessChoicePointName);
		if (login.isAdmin()) {
			((TextView) view.findViewById(R.id.fullname_assess)).setText(saveAssessTran.UserName);
			((TextView) view.findViewById(R.id.group_assess)).setText(saveAssessTran.UserTypeName);
		} else {
			((TextView) view.findViewById(R.id.fullname_assess)).setText(login.User_Name);
			((TextView) view.findViewById(R.id.group_assess)).setText(login.User_Group_Name);
		}

		// is AssessTran submitted?
		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
			isSubmit = true;

		// Current-Suggestion
		getMainSuggestion(AssessItemChoice5018);

		listCurrentSuggestion(R.id.cur_comment_table, AssessItemChoice5018);

		Button commentAdd = (Button) view.findViewById(R.id.comment_add);
		Button commentDelete = (Button) view.findViewById(R.id.comment_delete);
		CheckBox commentAll = (CheckBox) view.findViewById(R.id.cur_sub_check);
		if (isSubmit) {
			commentAll.setVisibility(Button.GONE);
			commentAdd.setVisibility(Button.GONE);
			commentDelete.setVisibility(Button.GONE);
		} else {
			commentDelete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					final AlertDialog.Builder cancelConfirm = new AlertDialog.Builder(getActivity());

					cancelConfirm.setTitle(getString(R.string.alert_confirm_delete));
					cancelConfirm.setNegativeButton("Cancel", null);
					cancelConfirm.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int arg1) {
							// TODO Auto-generated method stub
							final TableLayout table = (TableLayout) getView().findViewById(R.id.cur_comment_table);
							// Inflate your row "template" and fill out the
							// fields.
							for (int index = 1; index < table.getChildCount(); index++) {
								TableRow row = (TableRow) table.getChildAt(index);
								CheckBox check = (CheckBox) row.findViewById(R.id.check_value);
								if (check != null)
									if (check.isChecked()) {
										table.removeView(row);

										deleteImage(currentSuggestList.get(index - 1));

										currentSuggestList.remove(index - 1);
										index--;
									}
							}

							// set Sorted Index
							for (int index = 1; index < table.getChildCount(); index++) {
								TableRow row = (TableRow) table.getChildAt(index);
								CheckBox check = (CheckBox) row.findViewById(R.id.check_value);
								if (check != null) {
									row.setTag(R.id.tag_first, String.valueOf(index));
									currentIndex = index;

									ImageView mCamera = (ImageView) row.findViewById(R.id.image_value);
									mCamera.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub

											AssessSuggestion5034 suggestSelected = currentSuggestList.get(currentIndex - 1);
											if (suggestSelected.SuggestBitmaps.size() != 0) {
												showImageDialog(table, true, currentSuggestList, currentIndex);
											} else {
												showImageChooser();
											}
										}
									});
								}
							}

							table.requestLayout();

							if (table.getChildCount() == 1) {
								WidgetUtil.setNoDataRow(CommentAssessFragment.this.getActivity(), getView(), R.id.cur_comment_table, 6, true);
							}
							table.requestLayout();

						}
					});
					cancelConfirm.show();
				}
			});

			commentAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
					// TODO Auto-generated method stub
					TableLayout table = (TableLayout) getView().findViewById(R.id.cur_comment_table);
					if (arg1) {
						// Inflate your row "template" and fill out the fields.
						for (int index = 1; index < table.getChildCount(); index++) {
							TableRow row = (TableRow) table.getChildAt(index);
							CheckBox check = (CheckBox) row.findViewById(R.id.check_value);
							check.setChecked(true);
						}
					} else {
						// Inflate your row "template" and fill out the fields.
						for (int index = 1; index < table.getChildCount(); index++) {
							TableRow row = (TableRow) table.getChildAt(index);
							CheckBox check = (CheckBox) row.findViewById(R.id.check_value);
							check.setChecked(false);
						}
					}
				}
			});
		}
		// Initial Prev-Suggestion
		WidgetUtil.setNoDataRow(getActivity(), view, R.id.prev_comment_table, 6, false);

		// Prev-Suggestion
		getPrevSuggestion(AssessItemChoice5018);

		Button saveBtn = (Button) getView().findViewById(R.id.save_suggest);
		if (isSubmit)
			saveBtn.setVisibility(Button.GONE);
		else
			saveBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					saveAssessTranStep3_SaveSuggestion();

					deleteImageConfirmed(deleteImageList);

					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
					fragmentTransaction.addToBackStack(null).replace(R.id.container, MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, true, curSubject))
						.commit();

				}

			});

		Button backBtn = (Button) getView().findViewById(R.id.cancel_suggest);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder cancelConfirm = new AlertDialog.Builder(getActivity());

				cancelConfirm.setTitle(getString(R.string.alert_confirm_cancel));
				cancelConfirm.setNegativeButton("Cancel", null);
				cancelConfirm.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {

						deleteImageConfirmed(tempImageList);

						FragmentManager fragmentManager = getFragmentManager();
						FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
						fragmentTransaction.addToBackStack(null).replace(R.id.container, MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, true, curSubject))
							.commit();

					}
				});
				cancelConfirm.show();

			}
		});

	}

	protected void commentAdd(String AssessItemName) {
		// TODO Auto-generated method stub
		AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
		alert.setTitle(AssessItemName);
		LayoutInflater factory = LayoutInflater.from(getActivity());
		inputEntryView = factory.inflate(R.layout.comment_assess_input, null);

		// Can choose standard or other
		final RadioButton mainRd = (RadioButton) inputEntryView.findViewById(R.id.main);
		final RadioButton notMainRd = (RadioButton) inputEntryView.findViewById(R.id.not_main);

		// Set Suggestion Spinner
		Spinner suggestionSpinner = (Spinner) inputEntryView.findViewById(R.id.comment_spinner);
		List<String> checkDup = new ArrayList<String>();
		List<SpinnerObject> arr = new ArrayList<SpinnerObject>();

		if (mainSuggestionList != null) {
			for (MainSuggestion main : mainSuggestionList.MainSuggestion) {
				String suggestionId = main.AssessSuggestionId;
				String suggestionDesc = main.AssessSuggestionDesc;
				String suggestionType = main.AssessSuggestionType;

				if (!checkDup.contains(suggestionDesc)) {
					arr.add(new SpinnerObject(suggestionId, suggestionDesc, suggestionType));
					checkDup.add(suggestionDesc);
				}
			}
		} else {
			notMainRd.setChecked(true);
			mainRd.setVisibility(RadioButton.GONE);
			notMainRd.setVisibility(RadioButton.GONE);

			((Spinner) inputEntryView.findViewById(R.id.comment_spinner)).setVisibility(Spinner.INVISIBLE);
			((TextView) inputEntryView.findViewById(R.id.grp_fix)).setVisibility(TextView.INVISIBLE);

			((EditText) inputEntryView.findViewById(R.id.comment_input)).setVisibility(Spinner.VISIBLE);
			((RadioGroup) inputEntryView.findViewById(R.id.grp_input)).setVisibility(RadioGroup.VISIBLE);
		}
		checkDup.clear();
		ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(getActivity(), android.R.layout.simple_spinner_dropdown_item, arr);
		arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		suggestionSpinner.setAdapter(arrAdt);

		suggestionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				SpinnerObject selected = ((SpinnerObject) parent.getSelectedItem());
				((TextView) inputEntryView.findViewById(R.id.grp_fix)).setText(selected.getValue());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		alert.setView(inputEntryView);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// String value = input.getText().toString();
				Spinner mMain;
				EditText mComment;
				EditText mSuggest;
				EditText mInstitute;
				RadioGroup mGroup;
				TextView mGroupFix;
				RadioButton mSelected;

				mMain = (Spinner) inputEntryView.findViewById(R.id.comment_spinner);
				mComment = (EditText) inputEntryView.findViewById(R.id.comment_input);
				mSuggest = (EditText) inputEntryView.findViewById(R.id.suggest_input);
				mInstitute = (EditText) inputEntryView.findViewById(R.id.institute_input);
				mGroup = (RadioGroup) inputEntryView.findViewById(R.id.grp_input);
				mGroupFix = (TextView) inputEntryView.findViewById(R.id.grp_fix);
				final TableLayout table = (TableLayout) getView().findViewById(R.id.cur_comment_table);

				WidgetUtil.initDataRow(getActivity(), getView(), R.id.cur_comment_table, true);
				// Inflate your row "template" and fill out the
				// fields.
				final TableRow row = (TableRow) LayoutInflater.from(CommentAssessFragment.this.getActivity()).inflate(R.layout.comment_assess_row, null);

				((TextView) row.findViewById(R.id.suggest_value)).setText(mSuggest.getText().toString());
				((TextView) row.findViewById(R.id.institue_value)).setText(mInstitute.getText().toString());

				if (mainRd.isChecked()) {
					SpinnerObject selected = ((SpinnerObject) mMain.getSelectedItem());
					((TextView) row.findViewById(R.id.comment_value)).setText(selected.getName());
					((TextView) row.findViewById(R.id.group_value)).setText(mGroupFix.getText().toString());
				} else {
					((TextView) row.findViewById(R.id.comment_value)).setText(mComment.getText().toString());
					int selectedId = mGroup.getCheckedRadioButtonId();
					mSelected = (RadioButton) inputEntryView.findViewById(selectedId);
					((TextView) row.findViewById(R.id.group_value)).setText(mSelected.getText().toString());
				}
				row.setTag(R.id.tag_first, String.valueOf(table.getChildCount()));
				ImageView mCamera = (ImageView) row.findViewById(R.id.image_value);
				mCamera.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						currentIndex = Integer.parseInt((String) row.getTag(R.id.tag_first));
						showImageChooser();
					}
				});

				// row.setBackgroundColor(getResources().getColor(
				// R.color.sub_bar));
				table.addView(row);
				table.requestLayout();

				// Add Comment-Row
				AssessSuggestion5034 currentSuggest = new AssessSuggestion5034();
				currentSuggest.AssessSuggestionIndex = "";
				if (mainRd.isChecked()) {
					SpinnerObject selected = ((SpinnerObject) mMain.getSelectedItem());
					currentSuggest.AssessSuggestionId = selected.getId();
				}
				currentSuggest.AssessSuggestionDesc = ((TextView) row.findViewById(R.id.comment_value)).getText().toString();
				currentSuggest.AssessSuggestionDetail = ((TextView) row.findViewById(R.id.suggest_value)).getText().toString();
				currentSuggest.AssessSuggestionOwner = ((TextView) row.findViewById(R.id.institue_value)).getText().toString();
				currentSuggest.AssessSuggestionType = ((TextView) row.findViewById(R.id.group_value)).getText().toString();
				if (mainRd.isChecked())
					currentSuggest.RESOURCE_TYPE = AppUtil.ID_5034;
				else
					currentSuggest.RESOURCE_TYPE = AppUtil.ID_5035;
				currentSuggestList.add(currentSuggest);
				return;
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				return;
			}
		});

		final AlertDialog dialog = alert.create();
		dialog.show();

		final List<View> errors = new ArrayList<View>();
		errors.add((EditText) inputEntryView.findViewById(R.id.comment_input));
		errors.add((EditText) inputEntryView.findViewById(R.id.suggest_input));
		errors.add((EditText) inputEntryView.findViewById(R.id.institute_input));

		WidgetUtil.validateMaxlengthData(getActivity(), (EditText) inputEntryView.findViewById(R.id.suggest_input), dialog, Integer.parseInt(getString(R.string.maxlength)), errors);
		WidgetUtil.validateMaxlengthData(getActivity(), (EditText) inputEntryView.findViewById(R.id.institute_input), dialog, Integer.parseInt(getString(R.string.maxlength)), errors);

		if (mainSuggestionList == null) {
			WidgetUtil.validateMaxlengthData(getActivity(), (EditText) inputEntryView.findViewById(R.id.comment_input), dialog, Integer.parseInt(getString(R.string.maxlength)), errors);
			WidgetUtil.validateRequireData(getActivity(), (EditText) inputEntryView.findViewById(R.id.comment_input), dialog, errors);
		}
		mainRd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			boolean isFirst = true;

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				if (arg1) {
					((Spinner) inputEntryView.findViewById(R.id.comment_spinner)).setVisibility(Spinner.VISIBLE);
					((TextView) inputEntryView.findViewById(R.id.grp_fix)).setVisibility(TextView.VISIBLE);

					((EditText) inputEntryView.findViewById(R.id.comment_input)).setVisibility(Spinner.INVISIBLE);
					((RadioGroup) inputEntryView.findViewById(R.id.grp_input)).setVisibility(RadioGroup.INVISIBLE);

					dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
					boolean isFirstIndex = true;
					for (View errorView : errors) {
						EditText error = (EditText) errorView;
						if (error.getError() != null && !isFirstIndex) {
							dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
							break;
						}
						isFirstIndex = false;
					}

				} else {
					((Spinner) inputEntryView.findViewById(R.id.comment_spinner)).setVisibility(Spinner.INVISIBLE);
					((TextView) inputEntryView.findViewById(R.id.grp_fix)).setVisibility(TextView.INVISIBLE);

					((EditText) inputEntryView.findViewById(R.id.comment_input)).setVisibility(Spinner.VISIBLE);
					((RadioGroup) inputEntryView.findViewById(R.id.grp_input)).setVisibility(RadioGroup.VISIBLE);

					dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
					for (View errorView : errors) {
						EditText error = (EditText) errorView;
						if (error.getError() != null) {
							dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
							break;
						}
					}

					if (isFirst) {
						WidgetUtil.validateMaxlengthData(getActivity(), (EditText) inputEntryView.findViewById(R.id.comment_input), dialog, Integer.parseInt(getString(R.string.maxlength)), errors);
						WidgetUtil.validateRequireData(getActivity(), (EditText) inputEntryView.findViewById(R.id.comment_input), dialog, errors);
						isFirst = false;
					}
				}
			}
		});
	}

	private Bitmap handleResultFromCamera(Intent data) {
		// TODO Auto-generated method stub

		// get Camera
		Bitmap captureBmp = null;
		try {
			final File file = WidgetUtil.getTempFile(getActivity(), cameraFileName);
			captureBmp = WidgetUtil.adjustImage(Media.getBitmap(getActivity().getContentResolver(), Uri.fromFile(file)));
			WidgetUtil.bitmapToFile(getActivity(), captureBmp, cameraFileName);
			// do whatever you want with the bitmap (Resize, Rename, Add To
			// Gallery, etc)
		} catch (FileNotFoundException e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		}

		originalName = null;
		return captureBmp;
	}

	private Bitmap handleResultFromChooser(Intent data) {
		// TODO Auto-generated method stub

		// get Gallery
		try {
			Uri uriPath = data.getData();
			String[] arrFilePath = { MediaStore.Images.Media.DATA };

			Cursor cursor = getActivity().getContentResolver().query(uriPath, arrFilePath, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(arrFilePath[0]);
			String curImgFilePath = cursor.getString(columnIndex);
			cursor.close();

			originalName = curImgFilePath;

			// WidgetUtil.copyFile(getActivity(), curImgFilePath,
			// cameraFileName);
			Bitmap galleryBmp = WidgetUtil.adjustImage(BitmapFactory.decodeFile(curImgFilePath));
			WidgetUtil.bitmapToFile(getActivity(), galleryBmp, cameraFileName);

			return galleryBmp;
		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.alert_images_error), Toast.LENGTH_LONG).show();
			return null;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		try {
			super.onActivityResult(requestCode, resultCode, data);
			Bitmap takenPictureData = null;

			switch (requestCode) {

			case AppUtil.PICTURE_TAKEN_FROM_CAMERA:
				if (resultCode == Activity.RESULT_OK) {
					takenPictureData = handleResultFromCamera(data);
				}
				break;
			case AppUtil.PICTURE_TAKEN_FROM_GALLERY:
				if (resultCode == Activity.RESULT_OK) {
					takenPictureData = handleResultFromChooser(data);
				}
				break;
			}

			// And show the result in the image view.
			if (takenPictureData != null) {
				TableLayout table = (TableLayout) getView().findViewById(R.id.cur_comment_table);
				TableRow row = (TableRow) table.getChildAt(currentIndex);
				ImageView curImage = (ImageView) row.findViewById(R.id.image_value);
				curImage.setImageBitmap(takenPictureData);

				AssessSuggestion5034 selectedSuggest = currentSuggestList.get(currentIndex - 1);
				selectedSuggest.SuggestBitmaps.add(takenPictureData);
				selectedSuggest.SuggestBitmapKeys.add(cameraFileName);
				selectedSuggest.SuggestBitmapOrigKeys.add(originalName);
				selectedSuggest.CreateDt.add(AppUtil.EMPTY);
				showImageDialog(table, true, currentSuggestList, currentIndex);

				// For Cancel Suggestion
				tempImageList.add(cameraFileName);

				// CR 107, 108
				// uploadCall = UploadCall.getInstance();
				//
				// PropertyInfo nameProp = new PropertyInfo();
				// nameProp.setValue(cameraFileName);
				// nameProp.setType(String.class);
				//
				// PropertyInfo bitmapProp = new PropertyInfo();
				// bitmapProp.setValue((Bitmap) takenPictureData);
				// bitmapProp.setType(Bitmap.class);
				//
				// mTask = new DefaultTask(uploadCall,
				// getString(R.string.http_url));
				// mTask.delegate = fragment;
				// mTask.execute(nameProp, bitmapProp);
			}
		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.alert_images_error), Toast.LENGTH_LONG).show();
		}

	}

	private void showImageChooser() {
		// TODO Auto-generated method stub
		AlertDialog.Builder chooser = new AlertDialog.Builder(getActivity());
		chooser.setTitle(getString(R.string.chooser_title));
		LayoutInflater factory = LayoutInflater.from(getActivity());
		View imageEntryView = factory.inflate(R.layout.image_chooser, null);

		ImageView chooseSnap = (ImageView) imageEntryView.findViewById(R.id.snap);
		ImageView chooseGallery = (ImageView) imageEntryView.findViewById(R.id.gallery);

		chooser.setView(imageEntryView);
		final AlertDialog dialog = chooser.create();
		chooseSnap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
					Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					cameraFileName = UUID.randomUUID().toString() + AppUtil.JPG_TYPE;
					i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(WidgetUtil.getTempFile(getActivity(), cameraFileName)));
					startActivityForResult(i, AppUtil.PICTURE_TAKEN_FROM_CAMERA);
					dialog.dismiss();
				} catch (Exception e) {
					Toast.makeText(getActivity(), getString(R.string.alert_images_error), Toast.LENGTH_LONG).show();
				}
			}
		});

		chooseGallery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
					Intent i = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);
					cameraFileName = UUID.randomUUID().toString() + AppUtil.JPG_TYPE;
					startActivityForResult(i, AppUtil.PICTURE_TAKEN_FROM_GALLERY);
					dialog.dismiss();
				} catch (Exception e) {
					Toast.makeText(getActivity(), getString(R.string.alert_images_error), Toast.LENGTH_LONG).show();
				}
			}
		});

		dialog.show();
		dialog.getWindow().setLayout(480, ViewGroup.LayoutParams.WRAP_CONTENT);
	}

	private void showImageDialog(final TableLayout table, boolean isEdit, final List<AssessSuggestion5034> suggestionList, final int selectedIndex) {
		// TODO Auto-generated method stub
		AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
		LayoutInflater factory = LayoutInflater.from(getActivity());
		imageEntryView = factory.inflate(R.layout.image_slider, null);
		alert.setView(imageEntryView);

		final AlertDialog dialog = alert.create();

		if (!isEdit) {
			((ImageView) imageEntryView.findViewById(R.id.takeashot)).setVisibility(ImageView.INVISIBLE);
			((ImageView) imageEntryView.findViewById(R.id.trash)).setVisibility(ImageView.INVISIBLE);
		} else {
			TableRow row = (TableRow) table.getChildAt(selectedIndex);
			final ImageView mCamera = (ImageView) row.findViewById(R.id.image_value);
			ImageView mTakeashot = (ImageView) imageEntryView.findViewById(R.id.takeashot);
			ImageView mTrash = (ImageView) imageEntryView.findViewById(R.id.trash);

			AssessSuggestion5034 suggestSelected = currentSuggestList.get(currentIndex - 1);

			mCamera.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					TableRow selectedRow = (TableRow) arg0.getParent();
					AssessSuggestion5034 suggestSelected = currentSuggestList.get(Integer.parseInt((String) selectedRow.getTag(R.id.tag_first)) - 1);
					currentIndex = Integer.parseInt((String) selectedRow.getTag(R.id.tag_first));
					if (suggestSelected.SuggestBitmaps.size() != 0) {
						showImageDialog(table, true, suggestionList, selectedIndex);
					} else {
						showImageChooser();
					}
				}
			});

			if (Integer.parseInt(getString(R.string.max_images)) == suggestSelected.SuggestBitmapKeys.size()) {
				mTakeashot.setVisibility(ImageView.INVISIBLE);
			} else {
				mTakeashot.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						showImageChooser();
					}
				});
			}

			mTrash.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					AssessSuggestion5034 suggestSelected = currentSuggestList.get(currentIndex - 1);
					dialog.dismiss();

					ViewPager viewPager = (ViewPager) imageEntryView.findViewById(R.id.view_pager);

					deleteImage(suggestSelected.SuggestBitmapKeys.get(viewPager.getCurrentItem()));

					suggestSelected.SuggestBitmaps.remove(viewPager.getCurrentItem());
					suggestSelected.SuggestBitmapKeys.remove(viewPager.getCurrentItem());
					suggestSelected.SuggestBitmapOrigKeys.remove(viewPager.getCurrentItem());
					suggestSelected.CreateDt.remove(viewPager.getCurrentItem());
					if (suggestSelected.SuggestBitmaps.size() != 0) {
						showImageDialog(table, true, suggestionList, selectedIndex);
						mCamera.setImageBitmap(suggestSelected.SuggestBitmaps.get(suggestSelected.SuggestBitmaps.size() - 1));
					} else {
						mCamera.setImageResource(R.drawable.camera);
					}

				}
			});

		}

		AssessSuggestion5034 suggestSelected = suggestionList.get(selectedIndex - 1);

		TextView mImageCount = (TextView) imageEntryView.findViewById(R.id.image_count);
		mImageCount.setText(AppUtil.PATH + AppUtil.SPACE + AppUtil.SPACE + String.valueOf((suggestSelected.SuggestBitmapKeys.size())));

		ViewPager viewPager = (ViewPager) imageEntryView.findViewById(R.id.view_pager);
		ImageAdapter adapter = new ImageAdapter(getActivity(), suggestSelected.SuggestBitmaps);
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				TextView mImageIndex = (TextView) imageEntryView.findViewById(R.id.image_index);
				mImageIndex.setText(String.valueOf(arg0 + 1));

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		dialog.show();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View rootView = inflater.inflate(R.layout.comment_assess, container, false);
		return rootView;
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}

	private void getMainSuggestion(AssessItemChoice5018 item) {
		// TODO Auto-generated method stub
		PropertyInfo choiceProp = new PropertyInfo();
		choiceProp.setName(MainSuggestion.AssessChoiceIdParam);
		choiceProp.setValue(item.AssessChoiceId);
		choiceProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_listmainsuggestion));
		mTask.delegate = this;
		mTask.execute(choiceProp);
	}

	private void getPrevSuggestion(AssessItemChoice5018 item) {
		// TODO Auto-generated method stub

		try {
			PropertyInfo resourceProp = new PropertyInfo();
			resourceProp.setName(PriorSuggestion.AssessTran5016IdParam);
			resourceProp.setValue(saveAssessTran.RESOURCE_ID);
			resourceProp.setType(String.class);

			PropertyInfo subjectProp = new PropertyInfo();
			subjectProp.setName(PriorSuggestion.AssessSubjectIdParam);
			subjectProp.setValue(item.AssessSubjectId);
			subjectProp.setType(String.class);

			PropertyInfo choiceProp = new PropertyInfo();
			choiceProp.setName(PriorSuggestion.AssessChoiceIdParam);
			choiceProp.setValue(item.AssessChoiceId);
			choiceProp.setType(String.class);

			PropertyInfo stationProp = new PropertyInfo();
			stationProp.setName(PriorSuggestion.StationIdParam);
			stationProp.setValue(saveAssessTran.StationId);
			stationProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_listpriorsuggestion));
			mTask.delegate = this;
			mTask.execute(resourceProp, subjectProp, choiceProp, stationProp);
		} catch (Exception e) {
			Toast.makeText(getActivity(), "getPrevSuggestion Error", Toast.LENGTH_SHORT).show();
		}
	}

	private void deleteImage(AssessSuggestion5034 assessSuggestion5034) {
		// TODO Auto-generated method stub
		for (String imageKey : assessSuggestion5034.SuggestBitmapKeys) {
			deleteImage(imageKey);
		}
	}

	private void deleteImage(String imageKey) {
		// TODO Auto-generated method stub
		if (!deleteImageList.contains(imageKey))
			deleteImageList.add(imageKey);

	}

	private void deleteImageConfirmed(List<String> imageList) {
		for (String imageKey : imageList) {
			// Remove Image on Android
			// Temp
			WidgetUtil.deleteImageOnDevice(getActivity(), new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.image_path) + AppUtil.PATH
				+ imageKey));

			// Remove Image on Server
			PropertyInfo guidProp = new PropertyInfo();
			guidProp.setName(AppUtil.GuidFileName);
			guidProp.setValue(imageKey);
			guidProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_deleteimage));
			mTask.delegate = this;
			mTask.execute(guidProp);
		}
	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.method_listpriorsuggestion)))
				getListPriorSuggestion(method, output);
			else if (method.equals(getString(R.string.method_listmainsuggestion))) {
				getListMainSuggestion(method, output);
			} else if (method.equals(getString(R.string.http_url))) {
				UploadImage(method, output);
			} else if (method.equals(getString(R.string.method_deleteimage))) {
				DeleteImage(method, output);
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			if (method.startsWith(getString(R.string.img_url))) {
				DownloadImage(method, output, objects);
			}
		} catch (Exception e) {
		}
	}

	public void getListPriorSuggestion(String method, Object output) {
		try {
			PriorSuggestionList priorSuggestionList = (PriorSuggestionList) gson.fromJson((String) output, PriorSuggestionList.class);
			Log.i(method, String.valueOf(priorSuggestionList.PriorSuggestion.size()));
			if (priorSuggestionList.PriorSuggestion.size() != 0) {
				for (PriorSuggestion priorSuggestion : priorSuggestionList.PriorSuggestion) {
					AssessSuggestion5034 suggestion = new AssessSuggestion5034();
					suggestion.AssessSuggestionId = priorSuggestion.AssessSuggestionId;
					suggestion.AssessSuggestionIndex = priorSuggestion.AssessSuggestionIndex;
					suggestion.AssessSuggestionDesc = priorSuggestion.AssessSuggestionDesc;
					suggestion.AssessSuggestionDetail = priorSuggestion.AssessSuggestionDetail;
					suggestion.AssessSuggestionOwner = priorSuggestion.AssessSuggestionOwner;
					suggestion.AssessSuggestionType = priorSuggestion.AssessSuggestionType;
					suggestion.ImageKey = priorSuggestion.ImageKey;
					suggestion.Images = priorSuggestion.Images;
					priorSuggestList.add(suggestion);
				}

				listPriorSuggestion(R.id.prev_comment_table);
			}
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	public void getListMainSuggestion(String method, Object output) {
		try {
			mainSuggestionList = (MainSuggestionList) gson.fromJson((String) output, MainSuggestionList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}

		Button commentAdd = (Button) getView().findViewById(R.id.comment_add);
		commentAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AssessItemChoice5018 AssessItemChoice5018 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId).Items.get(0).AssessItemChoiceMap.get(itemId);
				commentAdd(AssessItemChoice5018.AssessItemName);
			}
		});
	}

	private void DownloadImage(String method, Object output, Object[] objects) {
		// TODO Auto-generated method stub
		try {
			ImageView img = (ImageView) objects[0];
			String tag = (String) objects[1];
			String filename = (String) objects[2];
			String origfilename = (String) objects[3];
			boolean isEdit = ((Boolean) objects[4]).booleanValue();
			TableRow row = (TableRow) objects[5];
			String createDt = (String) objects[6];

			if (isEdit) {
				AssessSuggestion5034 suggestion = currentSuggestList.get(Integer.parseInt(tag) - 1);
				suggestion.SuggestBitmaps.add((Bitmap) output);
				suggestion.SuggestBitmapKeys.add(filename);
				suggestion.SuggestBitmapOrigKeys.add(origfilename);
				suggestion.CreateDt.add(createDt);
			} else {
				AssessSuggestion5034 suggestion = priorSuggestList.get(Integer.parseInt(tag) - 1);
				suggestion.SuggestBitmaps.add((Bitmap) output);
				suggestion.SuggestBitmapKeys.add(filename);
				suggestion.CreateDt.add(createDt);
			}

			img.setImageBitmap((Bitmap) output);

			onDecrementCount(row, Integer.parseInt((String) row.getTag(R.id.tag_second)));
		} catch (Exception e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
		}

	}

	private boolean DownloadImageOnDevice(ImageView mCurrentImg, String filename, String origfilename, String tag, boolean isEdit, TableRow row, String createDt) {
		// TODO Auto-generated method stub
		try {

			Bitmap output = WidgetUtil.getImageOnDevice(getActivity(), filename);
			if (output != null) {

				if (isEdit) {
					AssessSuggestion5034 suggestion = currentSuggestList.get(Integer.parseInt(tag) - 1);
					suggestion.SuggestBitmaps.add(output);
					suggestion.SuggestBitmapKeys.add(filename);
					suggestion.SuggestBitmapOrigKeys.add(origfilename);
					suggestion.CreateDt.add(createDt);
				} else {
					AssessSuggestion5034 suggestion = priorSuggestList.get(Integer.parseInt(tag) - 1);
					suggestion.SuggestBitmaps.add(output);
					suggestion.SuggestBitmapKeys.add(filename);
					suggestion.SuggestBitmapOrigKeys.add(origfilename);
					suggestion.CreateDt.add(createDt);
				}

				mCurrentImg.setImageBitmap((Bitmap) output);

				onDecrementCount(row, Integer.parseInt((String) row.getTag(R.id.tag_second)));

				return true;
			}
		} catch (Exception e) {

		}
		return false;
	}

	private void DeleteImage(String method, Object output) {
		// TODO Auto-generated method stub
		Log.i(method, "Call WS Success");
	}

	private void UploadImage(String method, Object output) {
		// TODO Auto-generated method stub
		Log.i(method, "Call WS Success");
	}

	private void listPriorSuggestion(int priorTableId) {
		// TODO Auto-generated method stub
		final TableLayout table = (TableLayout) getView().findViewById(priorTableId);

		WidgetUtil.initDataRow(getActivity(), getView(), priorTableId, false);
		// Inflate your row "template" and fill out the
		// fields.

		for (AssessSuggestion5034 prior : priorSuggestList) {
			final TableRow row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.comment_assess_row, null);
			((CheckBox) row.findViewById(R.id.check_value)).setVisibility(CheckBox.GONE);
			((TextView) row.findViewById(R.id.comment_value)).setText(prior.AssessSuggestionDesc);
			((TextView) row.findViewById(R.id.suggest_value)).setText(prior.AssessSuggestionDetail);
			((TextView) row.findViewById(R.id.institue_value)).setText(prior.AssessSuggestionOwner);
			((TextView) row.findViewById(R.id.group_value)).setText(prior.AssessSuggestionType);

			row.setTag(R.id.tag_first, String.valueOf(table.getChildCount()));
			ImageView mPriorImg = (ImageView) row.findViewById(R.id.image_value);
			mPriorImg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					priorIndex = Integer.parseInt((String) row.getTag(R.id.tag_first));
					TableRow row = (TableRow) table.getChildAt(priorIndex);
					AssessSuggestion5034 suggestSelected = priorSuggestList.get(priorIndex - 1);
					if (suggestSelected.ImageKey != null && suggestSelected.ImageKey.length() != 0) {
						showImageDialog(table, false, priorSuggestList, priorIndex);
					}

				}
			});

			// Image Loading
			View mProgressView = row.findViewById(R.id.progress);
			View mContentView = row.findViewById(R.id.image_value);

			if (prior.ImageKey != null && prior.ImageKey.length() != 0) {

				WidgetUtil.showProgress(mContentView, mProgressView, true);
				row.setTag(R.id.tag_second, String.valueOf(prior.Images.get(0).SuggestionImage.size()));

				for (SuggestionImage suggestionImage : prior.Images.get(0).SuggestionImage) {
					if (!DownloadImageOnDevice(mPriorImg, suggestionImage.FILE_SAVE_NAME, suggestionImage.FILE_ORIGINAL_NAME, (String) row.getTag(R.id.tag_first), false, row,
						suggestionImage.CreatedDt)) {
						downloadCall = DownloadCall.getInstance();
						mTask = new DefaultTask(downloadCall, getString(R.string.img_url) + suggestionImage.FILE_SAVE_NAME, mPriorImg, row.getTag(R.id.tag_first), suggestionImage.FILE_SAVE_NAME,
							suggestionImage.FILE_ORIGINAL_NAME, Boolean.FALSE, row, suggestionImage.CreatedDt);
						mTask.delegate = fragment;
						mTask.execute();
					}

				}
			}

			row.setBackgroundResource(R.drawable.content_prev);
			table.addView(row);
		}
		table.requestLayout();

	}

	private void listCurrentSuggestion(int currentTableId, AssessItemChoice5018 AssessItemChoice5018) {
		// TODO Auto-generated method stub
		final TableLayout table = (TableLayout) getView().findViewById(currentTableId);

		// Empty Fields
		if (AssessItemChoice5018.Suggestions == null || AssessItemChoice5018.Suggestions.size() == 0 || AssessItemChoice5018.Suggestions.get(0).AssessSuggestion5034Map.size() == 0) {
			WidgetUtil.setNoDataRow(getActivity(), getView(), R.id.cur_comment_table, 6, true);
			return;
		}

		WidgetUtil.initDataRow(getActivity(), getView(), currentTableId, !isSubmit);

		Map<String, AssessSuggestion5034> AssessSuggestion5034Map = AssessItemChoice5018.Suggestions.get(0).AssessSuggestion5034Map;
		for (int index = 0; index < AssessSuggestion5034Map.size(); index++) {
			AssessSuggestion5034 current;
			if (AssessItemChoice5018.Suggestions != null && AssessItemChoice5018.Suggestions.get(0).AssessSuggestion5034 != null) {
				current = AssessItemChoice5018.Suggestions.get(0).AssessSuggestion5034.get(index);
			} else {
				current = AssessSuggestion5034Map.get(AppUtil.NEW_SUGGESTION + String.valueOf(index));
			}

			final TableRow row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.comment_assess_row, null);
			if (isSubmit)
				((CheckBox) row.findViewById(R.id.check_value)).setVisibility(CheckBox.GONE);
			((TextView) row.findViewById(R.id.comment_value)).setText(current.AssessSuggestionDesc);
			((TextView) row.findViewById(R.id.suggest_value)).setText(current.AssessSuggestionDetail);
			((TextView) row.findViewById(R.id.institue_value)).setText(current.AssessSuggestionOwner);
			((TextView) row.findViewById(R.id.group_value)).setText(current.AssessSuggestionType);

			row.setTag(R.id.tag_first, String.valueOf(table.getChildCount()));
			ImageView mCurrentImg = (ImageView) row.findViewById(R.id.image_value);
			mCurrentImg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					currentIndex = Integer.parseInt((String) row.getTag(R.id.tag_first));

					TableRow row = (TableRow) table.getChildAt(currentIndex);
					final ImageView mCamera = (ImageView) row.findViewById(R.id.image_value);
					final AssessSuggestion5034 suggestSelected = currentSuggestList.get(currentIndex - 1);

					if (suggestSelected.ImageKey != null && suggestSelected.ImageKey.length() != 0) {
						showImageDialog(table, !isSubmit, currentSuggestList, currentIndex);
					} else if (!isSubmit) {
						showImageChooser();
					}

				}
			});

			currentSuggestList.add(current);

			// Image Loading
			View mProgressView = row.findViewById(R.id.progress);
			View mContentView = row.findViewById(R.id.image_value);

			if (current.ImageKey != null && current.ImageKey.length() != 0) {

				WidgetUtil.showProgress(mContentView, mProgressView, true);
				row.setTag(R.id.tag_second, String.valueOf(current.Images.get(0).SuggestionImage.size()));

				// Toast.makeText(getActivity(),
				// String.valueOf(current.Images.get(0).SuggestionImage.size()),
				// Toast.LENGTH_LONG).show();

				for (SuggestionImage suggestionImage : current.Images.get(0).SuggestionImage) {
					if (!DownloadImageOnDevice(mCurrentImg, suggestionImage.FILE_SAVE_NAME, suggestionImage.FILE_ORIGINAL_NAME, (String) row.getTag(R.id.tag_first), true, row,
						suggestionImage.CreatedDt)) {
						downloadCall = DownloadCall.getInstance();
						mTask = new DefaultTask(downloadCall, getString(R.string.img_url) + suggestionImage.FILE_SAVE_NAME, mCurrentImg, (String) row.getTag(R.id.tag_first),
							suggestionImage.FILE_SAVE_NAME, suggestionImage.FILE_ORIGINAL_NAME, Boolean.TRUE, row, suggestionImage.CreatedDt);
						mTask.delegate = fragment;
						mTask.execute();
					}
				}
			}

			table.addView(row);
		}
		table.requestLayout();

	}

	private void saveAssessTranStep3_SaveSuggestion() {
		// TODO Auto-generated method stub
		AssessItemChoice5018 AssessItemChoice5018 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId).Items.get(0).AssessItemChoiceMap.get(itemId);
		AssessSuggestion5034List AssessSuggestion5034List = new AssessSuggestion5034List();
		for (int index = 0; index < currentSuggestList.size(); index++) {
			AssessSuggestion5034 suggestion = currentSuggestList.get(index);
			suggestion.AssessSuggestionIndex = String.valueOf(index);
			if (suggestion.SuggestBitmapKeys != null && suggestion.SuggestBitmapKeys.size() != 0) {
				int bitmapIndex = 0;
				suggestion.Images = new ArrayList<SuggestionImageList>();
				suggestion.Images.add(new SuggestionImageList());
				for (Bitmap bitmap : suggestion.SuggestBitmaps) {
					addSuggestionImage(suggestion.Images.get(0), bitmap, suggestion.SuggestBitmapKeys.get(bitmapIndex), suggestion.SuggestBitmapOrigKeys.get(bitmapIndex),
						suggestion.CreateDt.get(bitmapIndex));
					bitmapIndex++;
				}

				if (suggestion.ImageKey == null || suggestion.ImageKey.length() == 0)
					suggestion.ImageKey = UUID.randomUUID().toString();

			} else {
				suggestion.Images = new ArrayList<SuggestionImageList>();
				suggestion.ImageKey = null;
			}

			// Clear Bitmap
			suggestion.SuggestBitmaps.clear();
			suggestion.SuggestBitmapKeys.clear();
			suggestion.SuggestBitmapOrigKeys.clear();
			suggestion.CreateDt.clear();

			AssessSuggestion5034List.AssessSuggestion5034Map.put(AppUtil.NEW_SUGGESTION + String.valueOf(index), suggestion);

		}

		AssessItemChoice5018.Suggestions = new ArrayList<AssessSuggestion5034List>();
		AssessItemChoice5018.Suggestions.add(AssessSuggestion5034List);

		// Saved AssessTran Pref
		projCycleStationId = saveAssessTran.ProjectId + AppUtil.UNDER_SCROLL + saveAssessTran.CycleAssessId + AppUtil.UNDER_SCROLL + saveAssessTran.StationId + AppUtil.UNDER_SCROLL
			+ login.User_Group_Code;
		savedTranPref = new SavedAssessTran(getActivity().getApplicationContext());
		savedTranPref.saveMap(projCycleStationId, saveAssessTran);
	}

	private void addSuggestionImage(SuggestionImageList suggestImgs, Bitmap bitmap, String saveName, String origName, String createDt) {
		// TODO Auto-generated method stub
		SuggestionImage suggestionImg = new SuggestionImage();
		suggestionImg.Station_ID = saveAssessTran.StationId;
		suggestionImg.FILE_SAVE_NAME = saveName;
		suggestionImg.FILE_CONTENT_TYPE = AppUtil.JPG_CONTENT_TYPE;
		suggestionImg.FILE_SIZE = String.valueOf(bitmap.getByteCount());
		suggestionImg.RESOURCE_TYPENAME = getString(R.string.image_assess);
		suggestionImg.RESOURCE_DESCRIPTION = AppUtil.EMPTY;
		suggestionImg.FILE_ORIGINAL_NAME = origName;
		suggestionImg.CreatedDt = createDt;

		suggestImgs.SuggestionImage.add(suggestionImg);
	}

	@Override
	public void setCount(int cnt) {

	}

	@Override
	public void onDecrementCount() {

	}

	@Override
	public void onDecrementCount(View view, int cnt) {
		// TODO Auto-generated method stub
		TableRow row = (TableRow) view;
		row.setTag(R.id.tag_second, String.valueOf(--cnt));
		if (cnt <= 0) {
			View mContentView = ((TableRow) view).findViewById(R.id.image_value);
			View mProgressView = ((TableRow) view).findViewById(R.id.progress);

			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}
	}

	@Override
	public void onDecrementCount(boolean flag) {
		// TODO Auto-generated method stub

	}

}
